<template>
  <view
    :scale="scale"
    :change:scale="movable.setScale(scale)"
    class="movable-area"
    id="movable-area"
    :style="{
      width: areaWidth ? areaWidth + 'px' : 'auto',
      height: areaHight ? areaHight + 'px' : 'auto',
      backgroundColor: bgColor
    }"
  >
    <view
      class="movable-view"
      @touchstart="movable.onTouchStart"
      @touchmove="movable.onTouchMove"
      :style="{
        top: `${boxStyle.y}px`,
        left: `${boxStyle.x}px`,
        transform: `scale(${scale})`
      }"
      id="movable-view"
      style="transform-origin: 0 0"
    >
      <slot></slot>
    </view>
  </view>
</template>

<script module="movable" lang="wxs" src="./movable.wxs"></script>

<script>
export default {
  props: {
    bgColor: {
      type: String,
      default: '#e5e5e5'
    },
    scale: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      boxStyle: {
        x: 0,
        y: 0,
        tx: 0,
        ty: 0,
        scale: 1
      },
      windowWidth: 0,
      width: 0,
      height: 0,
      areaWidth: 0,
      areaHight: 0,
      distance: 0, //两指直接的距离
      startXY: {
        x: 0,
        y: 0
      },
      doubleFinger: false
    }
  },
  watch: {
    scale: {
      handler(newVal, oldVal) {
        if (newVal !== oldVal) {
          this.init()
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    init() {
      uni.getSystemInfo({
        success: (e) => {
          this.windowWidth = e.windowWidth
          this.areaWidth = Math.floor(e.windowWidth)
          this.areaHight = Math.floor(e.windowHeight)
        }
      })
    },
    getTree() {
      this.$nextTick(() => {
        this.setWH()
      })
    },
    setWH() {
      uni
        .createSelectorQuery()
        .in(this)
        .select('#movable-view')
        .boundingClientRect((data) => {
          this.width = data.width
          this.height = data.height
          this.boxStyle.x = this.windowWidth / 2 - this.width / 2
        })
        .exec()
    },
    setXYPoi(x, y) {
      this.boxStyle.x = this.areaWidth / 2 - x
      this.boxStyle.y = this.areaHight / 2 - y
    },
    logWxsData(arr) {
      console.log(...arr)
    }
  }
}
</script>

<style lang="scss" scoped>
.movable-area {
  position: relative;
  overflow: hidden;
  background-color: #ffffff;
  .movable-view {
    min-height: 100%;
    min-width: 100%;
    position: absolute;
    display: inline-block;
    overflow: hidden;
    // background: #F0AD4E;
    top: 0;
    left: 0;
  }
}
</style>
